import store from "../store";
import request from "../utils/request";

import md5 from "md5-js";

function collection() {
  // return db.collection(DB).doc(hasLoginState().user.uid);
}
/**
 * 用户新建和更新信息的接口
 * @param data
 * @returns {Promise<unknown>}
 */
export function addUserInfo(data) {
  // const {
  //   uid, avatarUrl, nickName, email, loginType, openid, wxOpenId,
  // } = data
  return new Promise((resolve, reject) => {
    resolve();
    // const newData = {
    //   uid, avatarUrl, nickName, email, loginType, openid, wxOpenId,
    // }

    // db.collection(DB).doc(newData.uid).get().then((res) => {
    //   console.log('用户日志-->', res)
    //   if (res.data.length < 1) {
    //     newData.firstTime = Date.now()
    //     db.collection(DB).doc(newData.uid).set(
    //       newData,
    //     ).then((res) => {
    //       resolve(res)
    //     })
    //       .catch((err) => {
    //         console.log('err=>', err)
    //         reject(err)
    //       })
    //   } else {
    //     db.collection(DB).doc(newData.uid).update(
    //       newData,
    //     ).then((res) => {
    //       resolve(res)
    //     })
    //       .catch((err) => {
    //         console.log('err=>', err)
    //         reject(err)
    //       })
    //   }
    // })
  });
}

/**
 * 或取用户的list
 * @returns {Promise<cloudbase.database.GetRes>}
 */
export function getUserInfoList() {
  // return db.collection(DB)
  //   .skip(0)
  //   .limit(1000)
  //   .get();
}

/**
 * 用户访问页面的记录
 * @param uid
 * @param pageInfo
 * @returns {Promise<cloudbase.database.SetRes>}
 */
export function setUserInfoPageLog(pageInfo) {
  // pageInfo.time = Date.now();
  // const { uid } = hasLoginState().user;
  // return collection().update({
  //   pageLog: _.push(pageInfo),
  // });
}

/**
 * 增加赞美访问记录
 * @param uid
 * @param zanmeiInfo
 * @returns {Promise<cloudbase.database.SetRes>}
 */
export function setUserInfoZanMeiLog(zanmeiInfo) {
  // zanmeiInfo.time = Date.now();
  // return collection().update({
  //   zanmeiLog: _.push(zanmeiInfo),
  // });
}

/**
 * 根据uid获取用户的昵称和头像信息
 * @param uid
 */
export function getUserInfo(uid) {
  // return new Promise((resolve, reject) => {
  //   db.collection(DB).doc(uid).field({ avatarUrl: true, nickName: true }).get()
  //     .then((res) => {
  //       resolve(res.data[0]);
  //     })
  //     .catch((err) => {
  //       reject(false);
  //     });
  // });
}

/**
 * 歌单操作集合
 * @type {{add: (function(*): Promise<cloudbase.database.SetRes>), updateGeDanDatailList: (function(*, *): Promise<unknown>), set: (function(*, *=): Promise<cloudbase.database.SetRes>), edit: (function(*, *): Promise<unknown>), get: (function(): Promise<*>), clear: gedanController.clear, removeGeDanDatailList: (function(*=, *): Promise<*>), getGeDanDatailList: (function(*): Promise<*>), addGeDanDatailList: (function(*=, *=): Promise<*>), remove: (function(*): Promise<*>)}}
 */
const localGeDanName = "gedanlist";

export const gedanController = {
  localGeDanName: "gedanlist",
  set: (title, ids) => {
    const id = md5(Date.now().toString() + uid);
    console.log("ids-->", ids);
    const time = Date.now();
    // return collection().update({
    //   gedan: _.push({
    //     id,
    //     title,
    //     time,
    //     list: ids,
    //   }),
    // });
  },
  /**
   * 增加歌单
   * @param id
   * @returns {Promise<cloudbase.database.UpdateRes>}
   */
  add: async (title, id = null, list = null) => {
    if (!id) {
      id = md5(Date.now().toString());
    }

    const time = Date.now();
    let gedanLocal = localStorage.getItem(localGeDanName);
    if (gedanLocal === null) {
      gedanLocal = [];
    } else {
      gedanLocal = JSON.parse(gedanLocal);
    }
    gedanLocal.push({
      title,
      id,
      list: [],
      time,
    });
    console.log(gedanLocal);
    localStorage.setItem(localGeDanName, JSON.stringify(gedanLocal));

    const fingerprintId = store.getters.fingerprintId;

    try {
      await request.post("/star/h5/song_list", {
        fingerprintId,
        name: title,
        list,
      });
      return Promise.resolve();
    } catch (error) {
      return Promise.reject(error);
    }
  },
  edit: (id, title) =>
    new Promise((resolve, reject) => {
      request
        .put("/star/h5/song_list", {
          id,
          name: title,
        })
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject();
        });
      // collection().field({ gedan: true }).get().then((res) => {
      //   const data = res.data[0].gedan;
      //   data.forEach((item) => {
      //     if (item.id === id) {
      //       item.title = title;
      //     }
      //   });
      //   collection().update({
      //     gedan: data,
      //   }).then((res) => {
      //     resolve(res);
      //   });
      // })
      //   .catch((err) => {
      //     reject(err);
      //   });
    }),
  /**
   * 获取歌单列表
   * @returns {Promise<unknown>}
   */
  get: () =>
    new Promise((resolve, reject) => {
      // const localGeDanList = localStorage.getItem(localGeDanName)

      // if (localGeDanList) {
      //   let res = JSON.parse(localGeDanList)
      //   res = res.filter((item) => !['我的收藏'].includes(item.id))
      //   resolve(res)
      // } else {
      //   resolve([])
      // }

      request
        .get("/star/h5/song_list/list")
        .then((res) => {
          if (res && res.code == 200) {
            const list = res.rows.map((item) => {
              return {
                ...item,
                list: item.list ? item.list.split(",") : [],
                title: item.name,
              };
            });
            resolve(list);
          } else {
            resolve([]);
          }
        })
        .catch((err) => {
          reject(err);
        });
    }),
  clear: () => {},
  /**
   * 移除指定歌单
   * @param id
   * @returns {Promise<unknown>}
   */
  remove: (id) =>
    new Promise((resolve, reject) => {
      request
        .delete("/star/h5/song_list/" + id)
        .then((res) => {
          resolve();
        })
        .catch((err) => {
          reject(err);
        });

      // let lol = localStorage.getItem(localGeDanName)
      // lol = JSON.parse(lol)
      // lol = lol.filter((i) => i.id !== id)
      // localStorage.setItem(localGeDanName, JSON.stringify(lol))
      // resolve()
      // collection().field({ gedan: true }).get().then((res) => {
      //   const data = res.data[0]
      //   const newData = data.gedan.filter((i) => i.id !== id)
      //   collection().update({
      //     gedan: newData,
      //   }).then((upRes) => {
      //     resolve(upRes)
      //   })
      // })
      //   .catch((err) => {
      //     reject(err)
      //   })
    }),
  /**
   * 或取歌单详情
   * @param id [歌单id]
   * @param uid [用户的 uid ]
   * @returns {Promise<unknown>}
   */
  getGeDanDatailList: (id, uid) => {
    return new Promise((resolve, reject) => {
      if (id == "我的收藏") {
        request
          .get("/star/h5/song_list/by_name/" + id)
          .then((res) => {
            if (res && res.code == 200) {
              resolve({
                ...res.data,
                list: res.data.list ? res.data.list.split(",") : [],
                title: res.data.name,
              });
            } else {
              reject();
            }
          })
          .catch((err) => {
            reject(err);
          });

        return;
      }

      request
        .get("/star/h5/song_list/" + id)
        .then((res) => {
          console.log("歌单详情", res);
          if (res && res.code == 200) {
            resolve({
              ...res.data,
              list: res.data.list ? res.data.list.split(",") : [],
              title: res.data.name,
            });
          } else {
            reject();
          }
        })
        .catch((err) => {
          reject(err);
        });
    });

    // let lol = localStorage.getItem(localGeDanName)
    // lol = JSON.parse(lol)
    // if (!lol) {
    //   lol = [
    //     {
    //       title: '我的收藏',
    //       id: '我的收藏',
    //       list: [],
    //       time: 1686216972825,
    //     },
    //   ]
    //   localStorage.setItem(localGeDanName, JSON.stringify(lol))
    // }

    // const res = lol.filter((i) => i.id === id)
    // if (res.length > 0) {
    //   lol = lol.filter((i) => i.id === id)[0]
    //   return Promise.resolve(lol)
    // }

    // return Promise.reject()

    // uid = uid || hasLoginState().user.uid
    // return new Promise((resolve, reject) => {
    //   db.collection(DB).doc(uid).field({ gedan: true }).get()
    //     .then((res) => {
    //       const data = res.data[0]
    //       const { gedan } = data
    //       const result = gedan.filter((i) => i.id === id)[0]
    //       resolve(result || { title: '歌单已经被创建者删除', list: [], error: true })
    //     })
    //     .catch((err) => {
    //       reject(err)
    //     })
    // })
  },
  /**
   * 或取分享歌单详情
   * @param id [歌单id]
   * @returns {Promise<unknown>}
   */
  getShareGeDanDatailList: (uid, id) =>
    new Promise((resolve, reject) => {
      // db.collection(DB).doc(uid).field({ gedan: true }).get()
      //   .then((res) => {
      //     const data = res.data[0];
      //     const { gedan } = data;
      //     resolve(gedan.filter((i) => i.id === id)[0]);
      //   })
      //   .catch((err) => {
      //     reject(err);
      //   });
    }),
  /**
   * 修改歌单里面的list
   * @param id 歌单的id
   * @param ids 要更新的赞美条目
   */
  updateGeDanDatailList: (id, ids) =>
    new Promise((resolve, reject) => {
      request
        .put("/star/h5/song_list", {
          id,
          list: ids.join(","),
        })
        .then((res) => {
          resolve(res);
        })
        .catch((err) => {
          reject();
        });
    }),
  /**
   * 在歌单中新增歌曲
   * @param gedanId 歌单ID
   * @param zanmeiId 歌曲ID
   * @returns {Promise<unknown>}
   */
  addGeDanDatailList: (gedanId, zanmeiId) =>
    new Promise((resolve, reject) => {
      request
        .post("/star/h5/song_list/add_list", {
          id: gedanId,
          list: zanmeiId,
        })
        .then((res) => {
          resolve();
        })
        .catch((err) => {
          reject(err);
        });
    }),
  /**
   * 在歌单中移除指定歌曲
   * @param gedanId 歌单ID
   * @param zanmeiId 歌曲ID
   * @returns {Promise<unknown>}
   */
  removeGeDanDatailList: (gedanId, zanmeiId) =>
    new Promise((resolve, reject) => {
      console.log(gedanId, zanmeiId);

      request
        .delete("/star/h5/song_list/del_list", {
          data: {
            id: gedanId,
            list: zanmeiId,
          },
        })
        .then((res) => {
          resolve();
        })
        .catch((err) => {
          reject(err);
        });
    }),
  /**
   * 把别人的歌单，收藏成为我的歌单
   *
   */
  AddGeDansaveAsMe: (gedanId, shareUid) =>
    new Promise((resolve, reject) => {
      gedanController.getGeDanDatailList(gedanId, shareUid).then((res) => {
        const newData = { ...res };
        newData.id = md5(Date.now().toString());
        collection()
          .update({
            gedan: _.push(newData),
          })
          .then(() => {
            resolve(newData.id);
          })
          .catch((err) => {
            reject(err);
          });
      });
    }),

  async getShouCang() {
    const res = await request.get("/star/h5/song_list/get_shou_cang");

    return {
      ...res.data,
      list: res.data.list ? res.data.list.split(",") : [],
      title: res.data.name,
    };
  },
};
